import { Rule } from "../model/Rule";
import { addTaskParamRule, timingDataRule } from "../rules";

type ValidateRslt<T = any> = {
  valid: boolean;
  data: T;
  errorMsg?: string;
};

export function validateRule<T>(
  rule: Partial<Record<keyof T, Rule[]>>,
  data?: T
) {
  const rslt = {
    valid: false,
    data,
    errorMsg: "",
  };
  if (!rule) {
    rslt.valid = true;
    return rslt;
  }
  if (!data || typeof data !== "object") {
    rslt.errorMsg = "参数为空";
    return rslt;
  }

  for (let name of Object.keys(rule)) {
    const rules = rule[name as keyof typeof rule] || [];
    // 目前指处理必填项
    for (let r of rules) {
      if (r.required && [undefined, "", null].includes((data as any)[name])) {
        rslt.valid = false;
        rslt.errorMsg = `字段 ${name} 校验未通过：${r.msg}`;
        return rslt;
      }
    }
  }

  rslt.valid = true;
  return rslt;
}

export function validateTimingData(data: any): ValidateRslt {
  return validateRule(timingDataRule, data);
}

export function validateAddTaskParam(data?: any): ValidateRslt {
  return validateRule(addTaskParamRule, data);
}
